
import config from "./config.json";

uni.REQUEST_URL = config.REQUEST_URL;

export const transformQueryString = (params) => {
  if (typeof params === "string") {
    const queryStrings = params.match(/[^?&]+=[^?&]+/g);

    return queryStrings ? Object.fromEntries(
      queryStrings.map(item => item.split(/^([^=]*)=*/).filter(item => item))
    ) : {};
  }

  if (typeof params === "object") {
    return Object.keys(params).filter(key => params[key]).map(key => `${key}=${params[key]}`).join("&");
  }

  throw Error("Parameter error");
}

export const pageData = (page = -2) => {
  const pages = getCurrentPages();
  return pages[pages.length + page];
}

uni.fetch = (url, params = {}) => {
  const [success, { token }] = [params.success, uni.getStorageSync(config.tokenContainer)];
  params.url = uni.REQUEST_URL + url;
  params.method = params.method || "POST";
  params[config.mode] = Object.assign(token ? { token } : {}, params[config.mode]);
  params.success = res => {
    switch (Number(res[config.mode].code)) {
      case 404:
      case 300:
        uni.clearStorageSync();

        // #ifndef MP-WEIXIN
        uni.showToast({
          title: decodeURI(res[config.mode].msg),
          icon: "none",
          duration: 1200,
          success: () => setTimeout(() => uni.reLaunch({ url: config.loginPage }), 1200)
        });
        // #endif

        // #ifdef MP-WEIXIN
        uni.showToast({ title: decodeURI(res[config.mode].msg), icon: "none" });
        uni.login({
          success({ code }) {
            uni.request({
              url: uni.REQUEST_URL + "/api/login/weChat",
              method: "GET",
              data: { code },
              success: ({ data }) => {
                uni.setStorageSync("userInfo", data);
                const { route, options } = pageData(-1);
                uni.reLaunch({
                  url: `/${route}?${transformQueryString(options)}`,
                  success: uni.hideLoading,
                });
              },
            });
          },
        })
        // #endif
        break;
      case 200:
        success && success(res.data);
        break;
      case 100:
        break;
      default:
        uni.showToast({ title: decodeURI(res[config.mode].msg), icon: "none" });
        break;
    }
  };
  params.fail = params.fail || (res => uni.showToast({
    title: "服务器异常",
    icon: "none",
    complete: _ => console.log(res)
  }));
  return uni.request({ ...params });
};

uni.getDate = (type = "date", seperator = "-") => {
  const date = new Date();
  switch (type) {
    case "day":
      return `星期${"日一二三四五六".charAt(date.getDay())}`;
    case "time":
      const [Hour, Minute, Seconds] = [
        date.getHours(),
        date.getMinutes(),
        date.getSeconds()
      ];
      return `${Hour}${seperator}${Minute < 9 ? "0" + Minute : Minute}${seperator}${Seconds < 9 ? "0" + Seconds : Seconds}`;
    default:
      const [Year, Month, Day] = [
        date.getFullYear(),
        date.getMonth() + 1,
        date.getDate()
      ];
      return `${Year}${seperator}${Month < 9 ? "0" + Month : Month}${seperator}${Day < 9 ? "0" + Day : Day}`;
  }
}

uni.isPhoneNumber = str =>
  /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(str);

uni.isEmail = str =>
  /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(str);

uni.isIdCard = str =>
  /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(str);


